package Leetcode第一期;

/**
 * @author : K k
 * @date : 11:19 2020/9/11
 */
public class 二叉搜索树与双向链表_36 {
    Node pre=null, head=null; //pre作为尾节点，head作为头节点

    //中序遍历
    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        dfs(root);
        head.left = pre; //这时候的pre是尾巴节点
        pre.right = head;
        return head;
    }

    //中序遍历
    void dfs(Node cur) {
        if (cur == null) {
            return;
        }
        dfs(cur.left); // 左
        /*System.out.println(root.val); // 根*/
        if (pre != null) {
            pre.right = cur;//当前节点作为前驱节点pre的右边
        }
        else {
            head = cur;
        }
        cur.left = pre;//当前节点的前驱节点是pre
        pre = cur;
        dfs(cur.right); // 右
    }

    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    ;
}
